import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../common/extension/string_extension.dart';
import '../common/api_service.dart';
import '../common/constants.dart';
import '../common/images.dart';
import '../common/logger.dart';
import '../common/routes.dart';
import '../model/pipe_model.dart';
import '../model/tab_data_model.dart';
import '../utils/screen_util.dart';
import '../utils/utils.dart';

class PipeDataListPage extends StatefulWidget {
  final TabDataModel tabModel;

  const PipeDataListPage({super.key, required this.tabModel});

  @override
  State<PipeDataListPage> createState() => _PipeDataListPageState();
}

class _PipeDataListPageState extends State<PipeDataListPage> with AutomaticKeepAliveClientMixin {
  final List<PipeModel> _pipeList = [];
  final List<SubList> _subTagList = [];
  final ScrollController _scrollController = ScrollController();
  int _selectedIndex = 0;
  int _page = 1;
  String _selectedTagId = "";

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent) {
        _loadMoreData();
      }
    });

    _subTagList.clear();
    if (widget.tabModel.subList != null && widget.tabModel.subList!.isNotEmpty) {
      _subTagList.add(SubList("", "全部"));
      _subTagList.addAll(widget.tabModel.subList!);
    }

    _selectedTagId = widget.tabModel.id;
    _fetchData();
  }

  Future<void> _refreshData() async {
    _page = 1;
    _fetchData();
  }

  void _fetchData({bool isRefresh = true}) {
    ApiService().getTagPipeList(_selectedTagId, _page, (list) {
      if (list.length > 0) {
        _page++;
      }
      setState(() {
        if (isRefresh) {
          _pipeList.clear();
        }
        _pipeList.addAll(list);
      });
    }, () {
      logger.e("请求数据失败~");
    });
  }

  void _loadMoreData() {
    _fetchData(isRefresh: false);
  }

  _buildSubTabView() {
    if (_subTagList.isNotEmpty) {
      return SliverToBoxAdapter(
        child: Padding(
          padding: const EdgeInsets.fromLTRB(6, 4, 2, 4),
          child: SizedBox(
            height: 40,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: _subTagList.length,
              itemBuilder: (context, index) {
                return GestureDetector(
                  onTap: () {
                    setState(() {
                      _selectedIndex = index;
                    });

                    _page = 1;
                    var tag = _subTagList[index];
                    _selectedTagId = tag.id == "" ? widget.tabModel.id : tag.id;
                    _fetchData();
                  },
                  child: Padding(
                    padding: const EdgeInsets.symmetric(vertical: 4, horizontal: 6.0),
                    child: Container(
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(20.0),
                        border: Border.all(
                          color: _selectedIndex == index ? Constants.themeColor : const Color(0xFFE0E0E0),
                          width: 1.0,
                        ),
                      ),
                      child: Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 10.0),
                        child: Center(
                          child: Text(
                            _subTagList[index].tag,
                            style: TextStyle(fontSize: 14, color: _selectedIndex == index ? Constants.themeColor : Colors.black54),
                            // 文字居中
                          ),
                        ),
                      ),
                    ),
                  ),
                );
              },
            ),
          ),
        ),
      );
    } else {
      return const SliverToBoxAdapter(child: SizedBox.shrink());
    }
  }

  @override
  void dispose() {
    super.dispose();
    _scrollController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    final screenWidth = ScreenUtil.getScreenWidth(context);
    var width = (screenWidth - 12.0) * 0.5;
    var height = width * 16 / 11;
    var h = height + 70;
    double ratio = width / h;
    return RefreshIndicator(
        onRefresh: _refreshData,
        displacement: 20,
        child: CustomScrollView(
          controller: _scrollController,
          slivers: [
            _buildSubTabView(),
            SliverPadding(
              padding: const EdgeInsets.fromLTRB(4, 4, 4, 0),
              sliver: SliverGrid(
                gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 2,
                  mainAxisSpacing: 0,
                  crossAxisSpacing: 4,
                  childAspectRatio: ratio,
                ),
                delegate: SliverChildBuilderDelegate(
                  (BuildContext context, int index) {
                    var pipe = _pipeList[index];
                    return HomePipeCard(width: width, height: height, pipe: pipe, showSummary: false);
                  },
                  childCount: _pipeList.length,
                ),
              ),
            )
          ],
        ));
  }
}

class HomePipeCard extends StatelessWidget {
  final double width;
  final double height;
  final PipeModel pipe;
  final bool showSummary;

  const HomePipeCard({super.key, required this.width, required this.height, required this.pipe, required this.showSummary});

  @override
  Widget build(BuildContext context) {
    final useNum = Utils.formatNumber(pipe.useNum ?? 0);
    final cover = pipe.cover.getThumbUrl(size: 500);
    final cartoonAvatar = pipe.cartoonAvatar == null ? "" : pipe.cartoonAvatar!.getThumbUrl(size: 100);
    final avatar = pipe.user?.avatar?.getThumbUrl(size: 100) ?? "";
    return InkWell(
        child: Container(
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Stack(
                children: <Widget>[
                  ClipRRect(
                    borderRadius: BorderRadius.circular(12.0),
                    child: Stack(
                      children: [
                        CachedNetworkImage(
                          width: width,
                          height: height,
                          fit: BoxFit.cover,
                          fadeInDuration: const Duration(milliseconds: 100),
                          fadeOutDuration: const Duration(seconds: 0),
                          imageUrl: cover,
                          placeholder: (context, url) {
                            return Container(
                              color: Colors.grey[50],
                              child: const Center(
                                child: Text(
                                  "FlowGPT",
                                  style: TextStyle(color: Colors.white, fontSize: 24, fontStyle: FontStyle.italic, shadows: [Shadow(color: Colors.black12, blurRadius: 1, offset: Offset(1.0, 1.0))]),
                                ),
                              ),
                            );
                          },
                          errorWidget: (_, url, object) {
                            return Container(
                              color: Colors.grey[50],
                              child: const Center(
                                child: Text(
                                  "FlowGPT",
                                  style: TextStyle(color: Colors.white, fontSize: 24, fontStyle: FontStyle.italic, shadows: [Shadow(color: Colors.black12, blurRadius: 1, offset: Offset(1.0, 1.0))]),
                                ),
                              ),
                            );
                          },
                        ),
                        if (cartoonAvatar.isNotEmpty)
                          Container(
                            height: 70,
                            decoration: const BoxDecoration(
                              gradient: LinearGradient(
                                colors: [Colors.black87, Colors.transparent],
                                begin: Alignment.topCenter,
                                end: Alignment.bottomCenter,
                              ),
                            ),
                          ),
                      ],
                    ),
                  ),
                  if (cartoonAvatar.isNotEmpty)
                    Positioned(
                      left: 12,
                      top: 12,
                      child: GestureDetector(
                          onTap: () {
                            var cartoonId = pipe.cartoonId ?? "";
                            Get.toNamed(Routes.CARTOON_INFO, arguments: {"cartoonId": cartoonId});
                          },
                          child: Container(
                            decoration: BoxDecoration(
                              border: Border.all(color: Colors.white, width: 1),
                              borderRadius: BorderRadius.circular(17),
                            ),
                            child: ClipRRect(
                              borderRadius: BorderRadius.circular(16),
                              child: CachedNetworkImage(
                                height: 32,
                                width: 32,
                                fadeInDuration: const Duration(seconds: 0),
                                fadeOutDuration: const Duration(seconds: 0),
                                fit: BoxFit.cover,
                                imageUrl: cartoonAvatar,
                                errorWidget: (_, url, object) {
                                  return Container(color: Colors.grey[200]);
                                },
                              ),
                            ),
                          )),
                    ),
                  Positioned(
                    left: 52,
                    top: 17,
                    child: Text(pipe.cartoonName ?? "", style: const TextStyle(color: Colors.white, fontSize: 14)),
                  ),
                ],
              ),
              Padding(
                padding: const EdgeInsets.fromLTRB(6, 5, 0, 0),
                child: showSummary
                    ? RichText(
                        text: TextSpan(
                          text: "",
                          children: <TextSpan>[
                            TextSpan(
                              text: pipe.name,
                              style: const TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
                            ),
                            TextSpan(
                              text: pipe.summary ?? "",
                              style: const TextStyle(color: Colors.black45),
                            )
                          ],
                        ),
                      )
                    : Text(pipe.name, maxLines: 1, overflow: TextOverflow.ellipsis),
              ),
              GestureDetector(
                  child: Padding(
                      padding: const EdgeInsets.fromLTRB(6, 5, 0, 0),
                      child: Row(
                        children: [
                          if (pipe.user != null)
                            ClipRRect(
                              borderRadius: BorderRadius.circular(15),
                              child: CachedNetworkImage(
                                height: 30,
                                width: 30,
                                fadeInDuration: const Duration(seconds: 0),
                                fadeOutDuration: const Duration(seconds: 0),
                                fit: BoxFit.cover,
                                imageUrl: avatar,
                                errorWidget: (_, url, object) {
                                  return Container(color: Colors.grey[200]);
                                },
                              ),
                            ),
                          if (pipe.user != null) const SizedBox(width: 5),
                          if (pipe.user != null) Expanded(child: Text(pipe.user?.nickname ?? "", style: const TextStyle(color: Colors.black54), overflow: TextOverflow.ellipsis)),
                          Image.asset(Images.pipe_chat, width: 16, height: 16, fit: BoxFit.cover),
                          Text(useNum, style: const TextStyle(color: Colors.black54))
                        ],
                      )),
                  onTap: () {
                    String uid = pipe.user?.uid ?? "";
                    if (uid.isNotEmpty) {
                      Get.toNamed(Routes.PROFILE, arguments: {"uid": uid});
                    }
                  })
            ],
          ),
        ),
        onTap: () {
          if (pipe.id != null) {
            var pipeId = pipe.id ?? "";
            Get.toNamed(Routes.CHAT, arguments: {"pipeId": pipeId});
          } else {
            var cartoonId = pipe.cartoonId ?? "";
            Get.toNamed(Routes.CARTOON_INFO, arguments: {"cartoonId": cartoonId});
          }
        });
  }
}
